import { BellOutlined, CopyOutlined, QuestionCircleOutlined } from '@ant-design/icons';
import { Badge, Drawer, Empty, List, Popover, Space, Timeline, Tooltip } from 'antd';
import { SelectLang, useModel } from 'umi';
import HeaderSearch from '../HeaderSearch';
import Avatar from './AvatarDropdown';
import styles from './index.less';
import { request } from 'umi';
import { history, Link } from 'umi';
import { forwardRef, useEffect, useImperativeHandle, useMemo, useRef, useState } from 'react';
export type SiderTheme = 'light' | 'dark';

const GlobalHeaderRight: React.FC = () => {
  const { initialState } = useModel('@@initialState');
  const [infocontent, setinfocontent] = useState('');
  const [list, setlist] = useState([]);
  const actionRef = useRef();
  if (!initialState || !initialState.settings) {
    return null;
  }

  const getNews = () => {
    request('/message/send/getUserPageList', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      data: {
        pageNo: 1,
        pageSize: 1000,
        "queryModeIds": [4],
        sendFlag: 0,
      }
    }).then((res) => {
      setlist(res?.data?.data || []);
    })
    // request('/message/send/getUserPageList', {
    //   method: 'POST',
    //   headers: {
    //     'Content-Type': 'application/json',
    //   },
    //   data: {
    //     "pageNo": 1,
    //     "pageSize": 20,
    //     "queryModeIds": [4]
    //   },
    // }).then((response) => {


    // })
  }
  const handleNew = (id) => {
    request('/message/send/edit', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      data: {
        id,
        "sendFlag": "1"
      }
    }).then((res) => {
      getNews()
    })
  }
  // useEffect(() => {
  //   getNews()
  // }, [])
  const { navTheme, layout } = initialState.settings;
  let className = styles.right;

  if ((navTheme === 'dark' && layout === 'top') || layout === 'mix') {
    className = `${styles.right}  ${styles.dark}`;
  }
  const content = <div className={styles.newsWrap}>
    <List
      itemLayout="horizontal"
      className={styles.list}
      dataSource={list}
      renderItem={(item, index) => (
        <List.Item>
          <List.Item.Meta
            onClick={() => handleNew(item.id)}
            title={<span>{item?.infoBO?.content}</span>}
            description={item.gmtCreate}
          />
        </List.Item>
      )}
    />
    <div onClick={() => { actionRef.current.init(); document.getElementById('cccccc').click() }} className={styles.history}>查看历史消息</div>
  </div>
  return (
    <Space className={className}>
      <CopyOutlined />
      <Avatar />
      <DrawerNewsCom ref={actionRef} />
      {/* 国际化 */}
      {/* <SelectLang className={styles.action} /> */}
    </Space>
  );
};
export default GlobalHeaderRight;

let scrollTime2 = null;

const DrawerNews = (props: any, refs: any) => {
  const [open, setOpen] = useState(false);
  const [page, setpage] = useState(0);
  const [totalCount, settotalCount] = useState(0)
  const [list, setlist] = useState([]);
  const [renLine, setrenLine] = useState([]);
  const showDrawer = () => {
    setOpen(true);
  };

  const onClose = () => {
    setOpen(false);
  };
  const getData = () => {
    request('/message/send/getUserPageList', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      data: {
        pageNo: page,
        pageSize: 30,
        "queryModeIds": [4]
      }
    }).then((res) => {
      if (page == 1) {
        setlist(res?.data?.data || []);
      } else {
        let nlist = res?.data?.data || [];
        setlist(list.concat(nlist));
      }

      settotalCount(res?.data?.totalCount);
    })
  }
  // useEffect(() => {
  //   getData();
  // }, [page]);
  const onmove = () => {
    if (scrollTime2 != null) {
      clearTimeout(scrollTime2)
    }
    scrollTime2 = setTimeout(() => {
      let element = document.getElementById('logNews');
      let isBottom = (element.scrollHeight - element.scrollTop) >= (element.clientHeight - 10);
      if (isBottom && (page * 10 < totalCount)) {
        console.log('到底了');
        if (list.length < totalCount) {
          setpage(page + 1);
        }

      }
    }, 500);
  }
  useImperativeHandle(refs, () => ({
    init: () => {
      setpage(1);
      setOpen(true);
      // setfileList([]);
    },
  }));
  // useEffect(() => {
  //   let arr = [];
  //   list.map((item, i) => {
  //     arr.push({
  //       color: 'green',
  //       children: <div key={i}>
  //         <span>{item?.infoBO?.content}</span>
  //         <span>{item?.gmtCreate}</span>
  //       </div>,
  //     },)
  //   })
  //   console.log(arr);
  //   setrenLine(arr);
  // }, [list])
  const sendMessageTypeColor = ['green', 'blue', 'yellow', 'oringe'];
  return (
    <>
      <Drawer title="历史消息" placement="right" onClose={onClose} open={open}>
        <div id='logNews' style={{ height: 'calc(100vh - 120px)', overflowY: 'auto' }} onTouchEnd={onmove} onScroll={onmove}>
          <Timeline

          >
            {
              list.map((item, i) => {
                return <Timeline.Item key={i} color={sendMessageTypeColor[item.sendMessageType]} label={item?.gmtCreat}>
                  <div key={i}>
                    <div>{item?.infoBO?.content}</div>
                    <div>{item?.gmtCreate}</div>
                  </div>
                </Timeline.Item>
              })
            }
          </Timeline>
          {/* <List
            itemLayout="horizontal"
            dataSource={list}
            renderItem={(item, index) => (
              <List.Item>
                <List.Item.Meta
                  title={<span>{item?.infoBO?.content}</span>}
                  description={item.gmtCreate}
                />
              </List.Item>
            )}
          /> */}
        </div>

      </Drawer>
    </>
  )
}

const DrawerNewsCom = forwardRef(DrawerNews);

export { DrawerNewsCom };
